﻿using System;
using System.Collections.Generic;
using System.Data.Entity.SqlServer;
using System.Linq;
using System.Web.Http;
using System.Web.Http.Controllers;
using Common.Logging;
using OutDbContext;
using User.Api.BizExtensions;
using User.Api.Dto.RegOrder;
using User.Api.Helpers;

namespace User.Api.Controllers
{
    public class RegOrderController : ApiController
    {
        private static readonly ILog Logger = LogManager.GetLogger(typeof(RegOrderController));
        private HzfyWeiXinEntities _ctx;

        protected override void Initialize(HttpControllerContext controllerContext)
        {
            _ctx = new HzfyWeiXinEntities();
            base.Initialize(controllerContext);
        }

        protected override void Dispose(bool disposing)
        {
            _ctx.Dispose();
            base.Dispose(disposing);
        }

        /// <summary>
        /// 获取所有挂号订单，只显示取号成功的订单
        /// </summary>
        /// <param name="type">current - 15内订单 history - 历史订单</param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("GetOrderList")]
        public GetOrderListResponse GetOrderList(string type = "current")
        {
            var azUser = AzUser.GetInApi(Request);
            List<ApptOrder> orders;

            if (type == "current")
            {
                orders =
                    _ctx.ApptOrder.Where(x => x.WxUserId == azUser.UserId).IsStatus(ApptOrderExtensions.OrderStatus.取号成功)
                        .Where(x => SqlFunctions.DateDiff("day", x.CreateTime, DateTime.Today) <= 15)
                        .OrderByDescending(x => x.RegDate).ThenByDescending(x => x.CreateTime).ToList();
            }
            else
            {
                orders =
                    _ctx.ApptOrder.Where(x => x.WxUserId == azUser.UserId).IsStatus(ApptOrderExtensions.OrderStatus.取号成功)
                        .Where(x => SqlFunctions.DateDiff("day", x.CreateTime, DateTime.Today) > 15)
                        .OrderByDescending(x => x.RegDate).ThenByDescending(x => x.CreateTime).ToList();
            }

            return new GetOrderListResponse
            {
                ResultCode = "0",
                ResultMsg = "",
                Orders = orders.Select(x => new GetOrderListResponse.Order
                {
                    OrderId = x.Id,
                    CardNo = x.CardNo,
                    CardName = x.CardName,
                    OrderNo = x.OrderNo,
                    CreateDt = x.CreateTime.GetValueOrDefault().ToString("yyyy-MM-dd HH:mm"),
                    RegDate = x.RegDate,
                    DeptName = x.DeptName,
                    DoctorName = x.DoctorName,
                    SumFee = x.SumFee.GetValueOrDefault(),
                    RegType = x.RegType
                }).ToList()
            };
        }

        /// <summary>
        /// 获取挂号订单详情
        /// </summary>
        /// <param name="orderId">订单Id</param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("GetOrderDetail")]
        public GetOrderDetailResponse GetOrderDetail(int orderId)
        {
            var azUser = AzUser.GetInApi(Request);
            var order = _ctx.ApptOrder.IsStatus(ApptOrderExtensions.OrderStatus.取号成功)
                .FirstOrDefault(x => x.WxUserId == azUser.UserId && x.Id == orderId);
            if (order == null)
            {
                return new GetOrderDetailResponse
                {
                    ResultCode = "1",
                    ResultMsg = "订单不存在"
                };
            }

            var regTime = "";
            if (string.IsNullOrEmpty(order.SuggestBeginTime))
            {
                regTime = string.IsNullOrEmpty(order.StartTime) ? "" : (order.StartTime + (string.IsNullOrEmpty(order.EndTime) ? "" : (" - " + order.EndTime)));
            }
            else
            {
                regTime = order.SuggestBeginTime + (string.IsNullOrEmpty(order.SuggestEndTime) ? "" : (" - " + order.SuggestEndTime));
            }

            bool canUnpickup = order.OrderType == ApptOrderExtensions.OrderType.预约.ToInt32().ToString()
    && string.CompareOrdinal(order.RegDate ?? "", DateTime.Today.ToString("yyyy-MM-dd")) > 0;

            bool effective = !(String.Compare(order.RegDate, DateTime.Now.ToString("yyyy-MM-dd"), StringComparison.Ordinal)<0);
            return new GetOrderDetailResponse
            {
                ResultCode = "0",
                ResultMsg = "",
                OrderId = order.Id,
                OrderNo = order.OrderNo,
                CardNo = order.CardNo,
                CardName = order.CardName,
                CreateDt = order.CreateTime.GetValueOrDefault().ToString("yyyy-MM-dd HH:mm"),
                OrderType = order.OrderType==ApptOrderExtensions.OrderType.预约.ToInt32().ToString()?
                    "预约挂号订单" : (order.OrderType == ApptOrderExtensions.OrderType.直接挂号.ToInt32().ToString() ?
                    "当天挂号订单" : "取号挂号订单"),
                RegDate = order.RegDate,
                DeptName = order.DeptName,
                DoctorName = order.DoctorName,
                RegType = order.RegType,
                SumFee = order.SumFee.GetValueOrDefault(),
                RegNo = order.RegNo,
                VisitNo = order.VisitNo,
                Loc = order.Location,
                RegTime = regTime,
                CanUnpickup = canUnpickup,
                Effective= effective
            };
        }
    }
}
